//
//  STMConsultManagementViewController.m
//  StoreManagement
//
//  Created by centling on 16/5/21.
//  Copyright © 2016年 alfred. All rights reserved.
//

#import "STMConsultManagementViewController.h"
#import "STMConsultTableViewCell.h"
#import "STMRefundAuditView.h"

@interface STMConsultManagementViewController ()<UITableViewDataSource, UITableViewDelegate, refundAuditViewDelegate>

@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) BOOL refreshing;

@property (nonatomic, strong) STMRefundAuditView *replyView;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, copy) NSString *storeId;
@property (nonatomic, copy) NSString *consultId;

@end

@implementation STMConsultManagementViewController


-(UIView *)maskView{
    if (!_maskView) {
        _maskView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        _maskView.backgroundColor=[UIColor blackColor];
        _maskView.alpha=0;
        UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(replyViewDisappear)];
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-108)];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    [self.mainTableView registerNib:[UINib nibWithNibName:@"STMConsultTableViewCell" bundle:nil] forCellReuseIdentifier:@"cellID"];
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.mainTableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.mainTableView.mj_footer.automaticallyChangeAlpha = YES;
    self.mainTableView.mj_footer.automaticallyHidden = NO;
    [self.view addSubview:self.mainTableView];
    self.page = 1;
    self.refreshing = NO;
    [self loadData];
}

- (void)loadData {
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getConsultManagementListWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                               storeId:@""
                                                  type:self.consultType
                                                  page:@"1"
                                               success:^(STMConsultManagementModel *result) {
                                                   self.refreshing = NO;
                                                   [self.mainTableView.mj_header endRefreshing];
                                                   if ([result.code isEqualToString:@"200"]) {
                                                       self.page = 1;
                                                       [SVProgressHUD dismiss];
                                                       self.dataArray = [NSMutableArray arrayWithArray:result.result.data];
                                                       [self.mainTableView reloadData];
                                                       if (self.dataArray.count < 10) {
                                                           [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                           self.mainTableView.mj_footer.alpha = 1;
                                                       } else {
                                                           [self.mainTableView.mj_footer resetNoMoreData];
                                                           self.mainTableView.mj_footer.alpha = 0;
                                                       }
                                                       
                                                   } else if ([result.code isEqualToString:@"401"]) {
                                                       STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
                                                       UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                                       loginVC.loginVCBlock = ^{
                                                           [nav popViewControllerAnimated:NO];
                                                       };
                                                       [nav presentViewController:loginVC animated:YES completion:nil];
                                                   } else {
                                                       [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                                   }
                                               }
                                               failure:^(NSError *err) {
                                                   self.refreshing = NO;
                                                   [self.mainTableView.mj_header endRefreshing];
                                                   [SVProgressHUD dismiss];
                                                   [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                               }];
    }
}

//上拉加载
- (void)loadMoreData {
    self.page ++;
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getConsultManagementListWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                               storeId:@""
                                                  type:self.consultType
                                                  page:[NSString stringWithFormat:@"%ld", self.page]
                                               success:^(STMConsultManagementModel *result) {
                                                   self.refreshing = NO;
                                                   [self.mainTableView.mj_footer endRefreshing];
                                                   if ([result.code isEqualToString:@"200"]) {
                                                       [SVProgressHUD dismiss];
                                                       NSArray *newArray = result.result.data;
                                                       if (newArray.count == 0) {
                                                           [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                           self.page --;
                                                           return;
                                                       } else {
                                                           [self.dataArray addObjectsFromArray:newArray];
                                                           NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
                                                           for (NSInteger i = [self.mainTableView numberOfRowsInSection:0]; i <[self.dataArray count]; i++){
                                                               [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i
                                                                                                                 inSection:0]];
                                                           }
                                                           [self.mainTableView beginUpdates];
                                                           [self.mainTableView insertRowsAtIndexPaths:arrayWithIndexPaths withRowAnimation:UITableViewRowAnimationNone];
                                                           [self.mainTableView endUpdates];
                                                       }
                                                       
                                                   } else if ([result.code isEqualToString:@"401"]) {
                                                       self.page --;
                                                       [GlobalUtil presentLoginVC];
                                                   } else {
                                                       self.page --;
                                                       [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                                   }
                                               }
                                               failure:^(NSError *err) {
                                                   self.page --;
                                                   self.refreshing = NO;
                                                   [self.mainTableView.mj_footer endRefreshing];
                                                   [SVProgressHUD dismiss];
                                                   [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                               }];
    }
}


- (void)replyViewDisappear {
    [self.maskView removeFromSuperview];
    self.maskView = nil;
    [self.replyView removeFromSuperview];
    self.replyView = nil;
}


#pragma mark -- replyViewDelegate
- (void)agreeOrDisagreeWithState:(NSString *)state Message:(NSString *)message returnType:(NSString *)returnType {
    if ([state isEqualToString:@"3"]) {
        [self replyViewDisappear];
        return;
    }
    [STMNetworkAPI consultReplyWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                               storeId:self.storeId
                             consultId:self.consultId
                               content:message
                               success:^(STMLoginModel *result) {
                                   [self replyViewDisappear];
                                   if ([result.code isEqualToString:@"200"]) {
                                       [self loadData];
                                   } else if ([result.code isEqualToString:@"401"]) {
                                       [GlobalUtil presentLoginVC];
                                   } else {
                                       [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                   }
                               }
                               failure:^(NSError *err) {
                                   [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                               }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    STMConsultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    STMConsultList *cellData = self.dataArray[indexPath.row];
    cell.consultType = self.consultType;
    cell.cellData = cellData;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __weak __typeof(self)weakSelf = self;
    cell.consultCellBlock = ^(NSString *storeId, NSString *consultId){
        weakSelf.storeId = storeId;
        weakSelf.consultId = consultId;
        weakSelf.replyView = [STMRefundAuditView refundAuditView];
        weakSelf.replyView.forConsultReply = YES;
        [weakSelf.replyView adjustForConsultReply];
        weakSelf.replyView.delegate = self;
        weakSelf.replyView.frame = CGRectMake(20, SCREEN_H/2-100, SCREEN_W-40, 200);
        [[[UIApplication sharedApplication] delegate].window addSubview:weakSelf.replyView];
        [([UIApplication sharedApplication].delegate).window insertSubview:weakSelf.maskView belowSubview:weakSelf.replyView];
        weakSelf.maskView.alpha = 0.4;
    };
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    STMConsultList *cellData = self.dataArray[indexPath.row];
    UILabel *tmpLabel = [[UILabel alloc] init];
    tmpLabel.font = [UIFont systemFontOfSize:13];
    tmpLabel.numberOfLines = 0;
    tmpLabel.lineBreakMode = NSLineBreakByCharWrapping;
    tmpLabel.text = cellData.consult.consult_content;
    CGSize maximumLabelSize = CGSizeMake(SCREEN_W - 16, 1000);
    CGSize expectContentLabelSize = [tmpLabel sizeThatFits:maximumLabelSize];
    tmpLabel.text = cellData.consult.consult_reply;
    CGSize expectReplyLabelSize = [tmpLabel sizeThatFits:maximumLabelSize];
    return 134+expectContentLabelSize.height+expectReplyLabelSize.height-32;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
